package MyTools;

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( fetchrow1col1_arrayref my_fetchall_arrayref);

use Data::Dumper;

sub fetchrow1col1_arrayref {
  my ($dbh, $sql, $col_hash) = @_;
  my ($sql_qual_str, $sql_bind) = make_place_holders($col_hash);
  $sql .= $sql_qual_str;
#  printf STDERR "$sql\n";
  my $sh = $dbh->prepare(qq{$sql}) or die "Couldn't prepare statement: " . $dbh->errstr;
  $sh->execute(@{$sql_bind}) or die "Couldn't execute statement: " . $sh->errstr;
#  my $ary_ref = $sh->fetchrow_arrayref();
  my $ary_ref = $sh->fetchall_arrayref();
  $sh->finish();
  die "===> MyTools.pm: More than one record found while one was expected. Here are two examples and the query\n===> $ary_ref->[0][0]\n$ary_ref->[1][0]\n$sql\n" if (scalar @{$ary_ref} > 1);
  return $ary_ref->[0][0];
}

sub make_place_holders {
	my ($col_hash) = @_;
	my ($sql_qual, $sql_bind);
  foreach my $col (keys %{$col_hash}) {
  	push @{$sql_qual}, "$col = ?";
  	push @{$sql_bind}, $col_hash->{$col};
  }
  my $sql_qual_str = join(" AND ", @{$sql_qual});
  return ($sql_qual_str, $sql_bind);
}

sub my_fetchall_arrayref {
  my ($dbh, $sql, $col_hash) = @_;
  my ($sql_qual_str, $sql_bind) = make_place_holders($col_hash);
  $sql .= $sql_qual_str;
  my $sh = $dbh->prepare(qq{$sql}) or die "Couldn't prepare statement: " . $dbh->errstr;
  $sh->execute(@{$sql_bind}) or die "Couldn't execute statement: " . $sh->errstr;
  my $ary_ref = $sh->fetchall_arrayref();
  $sh->finish();
  return $ary_ref;
}

1;

